<template>
  <div class="ele-singleUpload">
    <el-upload
      ref="uploadFile"
      class="upload-demo"
      action="#"
      :before-remove="beforeRemove"
      :limit="1"
      :http-request="submitUpload"
      list-type="picture"
    >
      <el-button type="primary">点击上传封面</el-button>
      <template #tip>
        <div class="el-upload__tip">图片大小不能超过5MB.</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { type UploadRequestOptions } from "element-plus"
import { InnerConfirm, messageReminder } from "@/utils/notificationHint"
import { uploadImageInCommunity } from "@/service/file/uploadFile"

import { onUnmounted, ref } from "vue"

import type { UploadInstance, UploadUserFile } from "element-plus"

const uploadFile = ref<UploadInstance>()

const fileList = ref<UploadUserFile[]>([])

const beforeRemove = (uploadFile, uploadFiles) => {
  return InnerConfirm(`确定删除图片 ${uploadFile.name} ?`)
    .then(() => {
      // 在 fileList 中查找并删除名为 uploadFile.name 的项
      const indexToRemove = fileList.value.findIndex((file) => file.url === uploadFile.url)
      if (indexToRemove !== -1) {
        uploadFiles.splice(indexToRemove, 1)
      }
      return true
    })
    .catch(() => {
      return false
    })
}

/**
 * 上传封面
 * @param content
 */
async function submitUpload(content: UploadRequestOptions) {
  const imgItem: UploadUserFile = {
    name: "",
    url: ""
  }
  imgItem.name = content.file.name

  const maxSize = 5
  // 判断图片大小
  if (content.file.size / 1024 / 1024 > maxSize) {
    messageReminder({
      message: "图片大小不能超过" + maxSize + "MB",
      type: "info"
    })
    return
  }

  // 创建一个FormData对象，用于封装表单数据
  const formData = new FormData()
  formData.append("singleFile", content.file)
  // 发送上传请求
  let result = await uploadImageInCommunity(formData, "Community")
  if (result.data.code == 200) {
    console.log("上传成功")
    imgItem.url = result.data.data

    fileList.value.push(imgItem)
  } else {
    messageReminder({
      message: "上传失败！" + result.data.message,
      type: "info"
    })
  }
}

// 清空文件列表
function clearFiles() {
  uploadFile.value!.clearFiles()
}

defineExpose({
  fileList,
  clearFiles
})
</script>

<style scoped>
/* 上传图片的样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
